package com.mvu.banana.common.widget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: mvu
 * Date: 4/22/11
 * Time: 11:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class Logo extends Composite {
  interface LogoUiBinder extends UiBinder<HTMLPanel, Logo> {
  }

  private static LogoUiBinder ourUiBinder = GWT.create(LogoUiBinder.class);

  @UiField
  Anchor englishLocale;
  @UiField
  Anchor vietnameseLocale;

  final String cookieName = LocaleInfo.getLocaleCookieName();
  final String queryParam = LocaleInfo.getLocaleQueryParam();

  public Logo() {
    initWidget(ourUiBinder.createAndBindUi(this));
  }

  @UiHandler("vietnameseLocale")
  void changeToVietnamese(ClickEvent e) {
    changeLocale("vi");
  }

  @UiHandler("englishLocale")
  void changeToEnglish(ClickEvent e) {
    changeLocale("en");
  }

  public void changeLocale(String localeName) {
    if (cookieName != null) {
      // expire in 100 days
      Date expires = new Date();
      expires.setTime(expires.getTime() * 864000000 * 10);
      Cookies.setCookie(cookieName, localeName, expires);
    }
    if (queryParam != null) {
      UrlBuilder builder = Window.Location.createUrlBuilder().setParameter(
              queryParam, localeName);
      Window.Location.replace(builder.buildString());
    } else {
      // If we are using only cookies, just reload
      Window.Location.reload();
    }
  }
}